using System;
using System.Windows;

namespace CuteConsole.Mvvm
{
  internal static class WindowModelHelper
  {
    // ReSharper disable AccessToModifiedClosure
    private static void HandleClose(Window window, WindowViewModel model)
    {
      EventHandler close = null;
      close = (s, e) =>
                {
                  model.RequestClose -= close;
                  window.Close();
                };
      model.RequestClose += close;
      window.Closed += (s, e) =>
                         {
                           window.DataContext = null;
                           model.RequestClose -= close;
                           model.Dispose();
                         };
    }
    // ReSharper restore AccessToModifiedClosure

    public static void Show(WindowViewModel model)
    {
      var tr = (TypeEntry)Application.Current.TryFindResource(model.GetType());
      Show(model, (Window)Activator.CreateInstance(tr.Value), tr.IsModal);
    }

    public static void Show(WindowViewModel model, Window window, bool isModal)
    {
      window.DataContext = model;
      SetOwner(window);
      HandleClose(window, model);
      Show(window, isModal);
    }

    private static void Show(Window window, bool modal)
    {
      if (modal) 
        window.ShowDialog(); 
      else 
        window.Show();
    }

    private static void SetOwner(Window window)
    {
      var mainWindow = Application.Current.MainWindow;
      if (window != mainWindow)
      {
        window.Owner = mainWindow;
      }
    }
  }
}